package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHHSTUtil
import cn.com.kh.KHUtil
import cn.com.kh.getProperty
import cn.com.kh.hst.ThreeDesUtil
import com.alibaba.fastjson.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.time.Instant

/**
 * @projectName: ngsapitask-hst
 * @package: cn.com.callback
 * @className: webchat
 * @author: HST
 * @description: 网聊进线主接口
 * @date: 2022-12-19 14:03
 * @version: 1.0
 */

public class webchat implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(webchat.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        log.debug("-------------------------start WebChat-----------------");//获取入参user

        String userid = request.getParameter("userid"); //华盛号
        String language = request.getParameter("language"); //访问语言
        String lang = request.getParameter("lang"); //访问语言
        String brand = request.getParameter("brand"); //brand
        //String areaid=request.getParameter("areaid"); //地区 DL大陆 HW海外 HK香港 AM澳门
        //String levelid=request.getParameter("levelid"); //会员等级 1普通 2白银 3黄金 4铂金 5钻石

        // WhatsApp进线时的参数信息
        String whapp_from = request.getParameter("from"); // WhatsApp客户手机
        String whapp_to = request.getParameter("to"); // WhatsApp发送到的账号
        String whapp_clientGuid = request.getParameter("clientGuid"); // WhatsApp发送到的账号

        // 非空保护
        whapp_from = KHUtil.isNull(whapp_from) ? "" : whapp_from;
        whapp_to = KHUtil.isNull(whapp_to) ? "" : whapp_to;
        log.debug("入参userid:" + userid + " 访问语言language：" + language + " brand：" + brand + " from：" + whapp_from + " to：" + whapp_to + " clientGuid：" + whapp_clientGuid);

        //埋点信息  有值进人工 无值则默认机器人排队
        String link = "";
        //新增客户归属部门 为空则按华盛通 Esop则按Esop客户
        String department = "";
        try {
            //替换中文符号
            brand = brand.replaceAll("“", "\"");
            log.debug("埋点信息-替换中文符号:" + brand);
            JSONObject jsonObject = JSONObject.parseObject(brand);
            link = jsonObject.get("link");
            department = jsonObject.get("department");

        } catch (Exception e) {
            link = "";
            department = "";
            log.warn("埋点信息-brand转Json对象异常！");
        }
        log.debug("埋点信息-处理后结果link:" + link + "    客户归属department:" + department);

        String areaid, areaname, levelname, password;
        String levelid = "";
        String outData = "";

        String queue = "";

        def type = "yyyy-MM-dd";
        def date = Util.getNowString(type);
        def cname = "SELITE";
        def customerguid, string9;

        log.debug("userid:" + userid);

        // 调用doWhatsAppMain检查处理,如果是WhatsApp进线子方法处理完成后直接返回,如果处理异常会返回userid默认常规调用
        JSONObject ws_ChatResult = doWhatsAppMain(eliteBean, jt, userid, whapp_from, whapp_to, department);
        log.debug("WhatsApp 进线逻辑处理结果:" + ws_ChatResult.toString());

        String ws_state = ws_ChatResult.getString("state");
        if (ws_state == "1") {
            return ws_ChatResult;
        } else if (ws_state == "0" && (KHUtil.isNull(userid) || userid == "undefined")) {
            userid = ws_ChatResult.getString("userid"); ;
            language = "102";
            log.debug("WhatsApp 进线逻辑处理结束:" + userid);
        }

        //区分客户校验
        if (department == "Esop") {
            if (userid != null && userid != "null" && userid != "undefined" && !userid.equals("")) {
                //根据传入rec_guid 获取sub 用户id
                def selectsubSql = "select sub from Kh_Oauth2_Cache where rec_guid= ? and DEL_FLAG='0' order by CREATETIME desc";
                log.debug("查询数据库中间表中是否有该sub:" + selectsubSql);
                def countsubsql = jt.queryForList(selectsubSql, userid);
                log.debug("查询数据库中间表中是否有该userid Result:" + countsubsql);
                //获取后直接更新为已提取
                def updatesubSql = "update Kh_Oauth2_Cache set DEL_FLAG='1'  where rec_guid= ?";
                def updatesubSqlResult = jt.update(updatesubSql, userid);
                log.debug("updatesubSql" + updatesubSql);
                log.debug("updatesubSqlResult" + updatesubSqlResult);
                //提取sub 给到userid
                userid = countsubsql[0].get("sub");
                log.debug("查询数据库中间表中userid :" + userid);

                //判断是否传userid。判断是否在customer表里能匹配到userid。如果能匹配到，就获取登录；如果匹配不到，就insert customer表
                if (userid != null && userid != "null" && userid != "undefined" && !userid.equals("")) {
                    // 查询数据库中是否有该userid
                    def selectopenSql = "Select Count(Distinct c.Customer_Guid) As countopenguid From Customer c Where Stringfield9 = ? and STRINGFIELD105='Esop'";
                    log.debug("查询数据库中是否有该userid SQL:" + selectopenSql);
                    def countopensql = jt.queryForList(selectopenSql, userid);
                    log.debug("查询数据库中是否有该userid Result:" + countopensql);
                    def map1 = countopensql[0];
                    def countopenguid = map1.get("countopenguid");
                    log.debug("判断客户customer_guid是否存在。不存在时新增；存在时查询 数量:" + countopenguid);

                    //判断本地是否有客户，无则新增
                    if (countopenguid == 0 || countopenguid.equals("0")) {
                        log.debug("不存在userid，新增customer表");
                        def openguid1 = Util.getGuid();

                        def custname = "网聊客户" + userid;
                        log.debug("openguid1:" + openguid1);
                        def insertopenSql = "INSERT INTO customer (customer_guid,CUSTOMER_ID,stringfield9,createddate,createdby,MODIFIEDDATE,MODIFIEDBY,customername,CUSTOMERID2,STRINGFIELD105)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,'Esop')";
                        def insertopenSqlResult = jt.update(insertopenSql, openguid1, userid, userid, date, cname, date, cname, custname, userid);
                        log.debug("insertopenSql" + insertopenSql);
                        log.debug("insertopenSqlResult" + insertopenSqlResult);
                        log.debug("customer表新增客户userid成功");

                        JSONObject jsonopenALL2 = new JSONObject();
                        jsonopenALL2.put("state", "1");
                        jsonopenALL2.put("success", "true");
                        //Esop 暂不区分客户等级 不区分等级队列
                        queue = 23;

                        jsonopenALL2.put("queue", queue);
                        jsonopenALL2.put("msg", "接口调用成功......");
                        log.debug("获取loginname和password");
                        JSONObject jsonopen1 = new JSONObject();
                        jsonopen1.put("loginName", userid);
                        jsonopen1.put("password", "");
                        jsonopenALL2.put("result", jsonopen1);
                        return jsonopenALL2;

                    } else {
                        //如存在则查询对应客户的信息
                        def selectcustSql = "Select Stringfield11,CUSTOMERID2 From Customer c Where Stringfield9 = ?";
                        log.debug("selectopenSql" + selectopenSql);
                        def custresultsql = jt.queryForList(selectcustSql, userid);
                        log.debug("custresultsql" + custresultsql);
                        def map2 = custresultsql[0];

                        password = map2.get("Stringfield11");
                        def CUSTOMERID2 = map2.get("CUSTOMERID2");
                        log.debug("password:" + password + "	,CUSTOMERID2:" + CUSTOMERID2);

                        //处理黑名单拉黑的CUSTOMERID2更新
                        if (CUSTOMERID2 == null || CUSTOMERID2.equals("")) {
                            def updateuserid = "update customer set CUSTOMERID2=? where stringfield9 =?";
                            def updateuseridresult = jt.update(updateuserid, userid, userid);
                            log.debug("updateuserid" + updateuserid);
                            log.debug("updateuseridresult" + updateuseridresult);
                            log.debug("customer表修改客户CUSTOMERID2成功");
                        }

                        //返回成功的查询结果
                        JSONObject jsonALL3 = new JSONObject();
                        jsonALL3.put("state", "1");
                        jsonALL3.put("success", "true");

                        log.debug("levelid:" + levelid);
                        //Esop 暂不区分客户等级 不区分等级队列
                        queue = 23;

                        jsonALL3.put("queue", queue);
                        jsonALL3.put("msg", "接口调用成功......");
                        JSONObject json2 = new JSONObject();
                        json2.put("loginName", userid);
                        json2.put("password", password);
                        jsonALL3.put("result", json2);
                        return jsonALL3;
                    }

                } else {
                    //Esop 暂不区分 进线语种 客户等级
                    queue = 23;
                    //返回失败的结果
                    JSONObject jsonALL1 = new JSONObject();
                    jsonALL1.put("queue", queue);
                    jsonALL1.put("state", "0");
                    jsonALL1.put("success", "false");
                    jsonALL1.put("msg", "接口调用失败,入参匹配不到相应客户......");
                    return jsonALL1;
                }

            } else {
                //Esop 暂不区分 进线语种 客户等级
                queue = 23;
                //返回失败的结果
                JSONObject jsonALL1 = new JSONObject();
                jsonALL1.put("queue", queue);
                jsonALL1.put("state", "0");
                jsonALL1.put("success", "false");
                jsonALL1.put("msg", "接口调用失败,入参匹配不到相应客户......");
                return jsonALL1;
            }

        } else {//按华盛通客户
            //判断是否传userid。判断是否在customer表里能匹配到userid。如果能匹配到，就获取登录；如果匹配不到，就insert customer表
            if (userid != null && userid != "null" && userid != "undefined" && !userid.equals("")) {

                // 查询数据库中是否有该userid
                def selectopenSql = "Select Count(Distinct c.Customer_Guid) As countopenguid From Customer c Where Stringfield9 = ? and stringfield105 is null";
                log.debug("查询数据库中是否有该userid SQL:" + selectopenSql);
                def countopensql = jt.queryForList(selectopenSql, userid);
                log.debug("查询数据库中是否有该userid Result:" + countopensql);
                def map1 = countopensql[0];
                def countopenguid = map1.get("countopenguid");
                log.debug("判断客户customer_guid是否存在。不存在时新增；存在时查询 数量:" + countopenguid);

                //鉴权变量
                String appid = getProperty.get("appid");
                String appsecret = getProperty.get("appsecret");

                //sign加密前后
                String signfront = "";
                String signafter = "";

                String sign_time = Instant.now().getEpochSecond();
                log.debug("解析信息-" + "sign_time: " + sign_time);

                HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                    {
                        put("sign_time", sign_time);
                        put("hsNo", userid);

                    }
                };

                log.debug("paramHashMap：" + paramHashMap);
                //自然排序 升序参数
                signfront = ThreeDesUtil.sortMap(paramHashMap, appid, appsecret);
                log.debug("sign加密MD5前：" + signfront);
                signafter = Util.getMD5Str(signfront);
                log.debug("sign加密MD5后：" + signafter);

                //拼接接口入参
                paramHashMap.put("client_key", appid);
                paramHashMap.put("sign", signafter);

                String injson = ThreeDesUtil.SplicingMap(paramHashMap, "&");
                log.debug("injson:" + injson);

                outData = Querypromocode(injson);

                //解析返回信息
                JSONObject jsonObject1 = JSONObject.parseObject(outData, Feature.OrderedField);
                String code = jsonObject1.get("code");
                String result = jsonObject1.get("result");
                if (code == "00000") {
                    JSONObject jsonObject = JSONObject.parseObject(result, Feature.OrderedField);
                    areaid = jsonObject.get("areaId");
                    areaname = jsonObject.get("areaName");
                    levelid = jsonObject.get("levelId");
                    levelname = jsonObject.get("levelName");
                    log.debug("areaid:" + areaid + "	areaname:" + areaname + "	levelid:" + levelid + "	levelname:" + levelname);

                    if (countopenguid == 0 || countopenguid.equals("0")) {
                        log.debug("不存在userid，新增customer表");
                        def openguid1 = Util.getGuid();

                        def custname = "网聊客户" + userid;
                        log.debug("openguid1:" + openguid1);
                        def insertopenSql = "INSERT INTO customer (customer_guid,CUSTOMER_ID,stringfield9,createddate,createdby,MODIFIEDDATE,MODIFIEDBY,customername,customerlevel,sq_15,sq_13,sq_14,CUSTOMERID2)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        def insertopenSqlResult = jt.update(insertopenSql, openguid1, userid, userid, date, cname, date, cname, custname, levelid, areaid, areaname, levelname, userid);
                        log.debug("insertopenSql" + insertopenSql);
                        log.debug("insertopenSqlResult" + insertopenSqlResult);
                        log.debug("customer表新增客户userid成功");

                        JSONObject jsonopenALL2 = new JSONObject();
                        jsonopenALL2.put("state", "1");
                        jsonopenALL2.put("success", "true");

                        log.debug("levelid:" + levelid);
                        //查询数据库中语言、会员等级匹配的队列queueid
                        queue = getqueueid(userid, language, levelid, link, jt);

                        // M+ 投资专区
                        if (whapp_from.equals("APPDR")) {
                            if (lang.equals("zh_cn") || lang.equals("zh_hk")) {
                                queue = 23;
                            } else {
                                queue = 22;
                            }
                        }
                        log.debug("M+ 投资专区队列识别: from:" + whapp_from + " lang:" + lang + " 识别结果queue:" + queue);

                        jsonopenALL2.put("queue", queue);
                        jsonopenALL2.put("msg", "接口调用成功......");
                        log.debug("获取loginname和password");
                        JSONObject jsonopen1 = new JSONObject();
                        jsonopen1.put("loginName", userid);
                        jsonopen1.put("password", "");
                        jsonopenALL2.put("result", jsonopen1);
                        return jsonopenALL2;

                    } else {

                        //更新levelid
                        if (levelid != null && !levelid.equals("")) {
                            def updateuserid = "update customer set customerlevel=?,sq_14=?, Icon_Url = Null where stringfield9 =? and stringfield105 is null";
                            def updateuseridresult = jt.update(updateuserid, levelid, levelname, userid);
                            log.debug("updateuserid" + updateuserid);
                            log.debug("updateuseridresult" + updateuseridresult);
                            log.debug("customer表修改客户levelid成功");
                        }
                        //更新地区
                        if (areaid != null && !areaid.equals("")) {
                            def updateuserid = "update customer set sq_15=?,sq_13=?, Icon_Url = Null where stringfield9 =? and stringfield105 is null";
                            def updateuseridresult = jt.update(updateuserid, areaid, areaname, userid);
                            log.debug("updateuserid" + updateuserid);
                            log.debug("updateuseridresult" + updateuseridresult);
                            log.debug("customer表修改客户areaid成功");
                        }

                        //获取当前账户密码
                        def selectcustpasswordSql = "Select Stringfield11,CUSTOMERID2 From Customer c Where Stringfield9 = ? and stringfield105 is null";
                        log.debug("selectcustpasswordSql" + selectcustpasswordSql);
                        def custpasswordresultsql = jt.queryForList(selectcustpasswordSql, userid);
                        log.debug("custpasswordresultsql" + custpasswordresultsql);
                        def map3 = custpasswordresultsql[0];
                        password = map3.get("Stringfield11");
                        def CUSTOMERID2 = map3.get("CUSTOMERID2");
                        log.debug("password:" + password + "CUSTOMERID2:" + CUSTOMERID2);

                        //处理黑名单拉黑的CUSTOMERID2更新
                        if (CUSTOMERID2 == null || CUSTOMERID2.equals("")) {
                            def updateuserid = "update customer set CUSTOMERID2=? where stringfield9 =? and stringfield105 is null";
                            def updateuseridresult = jt.update(updateuserid, userid, userid);
                            log.debug("updateuserid" + updateuserid);
                            log.debug("updateuseridresult" + updateuseridresult);
                            log.debug("customer表修改客户CUSTOMERID2成功");
                        }

                        //返回成功的查询结果
                        JSONObject jsonALL3 = new JSONObject();
                        jsonALL3.put("state", "1");
                        jsonALL3.put("success", "true");

                        log.debug("levelid:" + levelid);
                        //查询数据库中语言、会员等级匹配的队列queueid
                        queue = getqueueid(userid, language, levelid, link, jt);

                        // M+ 投资专区
                        if (whapp_from.equals("APPDR")) {
                            if (lang.equals("zh_cn") || lang.equals("zh_hk")) {
                                queue = 22;
                            } else {
                                queue = 21;
                            }
                        }
                        log.debug("M+ 投资专区队列识别: from:" + whapp_from + " lang:" + lang + " 识别结果queue:" + queue);

                        jsonALL3.put("queue", queue);
                        jsonALL3.put("msg", "接口调用成功......");
                        JSONObject json2 = new JSONObject();
                        json2.put("loginName", userid);
                        json2.put("password", password);
                        jsonALL3.put("result", json2);
                        return jsonALL3;
                    }
                } else {//调度接口失败
                    //判断本地是否有客户，无则新增
                    if (countopenguid == 0 || countopenguid.equals("0")) {
                        log.debug("不存在userid，新增customer表");
                        def openguid1 = Util.getGuid();

                        def custname = "网聊客户" + userid;
                        log.debug("openguid1:" + openguid1);
                        def insertopenSql = "INSERT INTO customer (customer_guid,CUSTOMER_ID,stringfield9,createddate,createdby,MODIFIEDDATE,MODIFIEDBY,customername,customerlevel,sq_15,sq_13,sq_14,CUSTOMERID2)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        def insertopenSqlResult = jt.update(insertopenSql, openguid1, userid, userid, date, cname, date, cname, custname, levelid, areaid, areaname, levelname, userid);
                        log.debug("insertopenSql" + insertopenSql);
                        log.debug("insertopenSqlResult" + insertopenSqlResult);
                        log.debug("customer表新增客户userid成功");

                        JSONObject jsonopenALL2 = new JSONObject();
                        jsonopenALL2.put("state", "1");
                        jsonopenALL2.put("success", "true");
                        queue = 1;

                        // M+ 投资专区
                        if (whapp_from.equals("APPDR")) {
                            if (lang.equals("zh_cn") || lang.equals("zh_hk")) {
                                queue = 22;
                            } else {
                                queue = 21;
                            }
                        }
                        log.debug("M+ 投资专区队列识别: from:" + whapp_from + " lang:" + lang + " 识别结果queue:" + queue);

                        jsonopenALL2.put("queue", queue);
                        jsonopenALL2.put("msg", "接口调用成功......");
                        log.debug("获取loginname和password");
                        JSONObject jsonopen1 = new JSONObject();
                        jsonopen1.put("loginName", userid);
                        jsonopen1.put("password", "");
                        jsonopenALL2.put("result", jsonopen1);
                        return jsonopenALL2;

                    } else {
                        //如存在则查询对应客户的信息
                        def selectcustSql = "Select customerlevel, sq_15, sq_13, sq_14 ,Stringfield11,CUSTOMERID2 From Customer c Where Stringfield9 = ? and stringfield105 is null";
                        log.debug("selectopenSql" + selectopenSql);
                        def custresultsql = jt.queryForList(selectcustSql, userid);
                        log.debug("custresultsql" + custresultsql);
                        def map2 = custresultsql[0];
                        levelid = map2.get("customerlevel");
                        areaid = map2.get("sq_15");
                        areaname = map2.get("sq_13");
                        levelname = map2.get("sq_14");
                        password = map2.get("Stringfield11");
                        def CUSTOMERID2 = map2.get("CUSTOMERID2");
                        log.debug("levelid:" + levelid + "	,areaid:" + areaid + "	,areaname:" + areaname + "	,levelname:" + levelname + "	,password:" + password + "	,CUSTOMERID2:" + CUSTOMERID2);

                        //null判定
                        if (levelid == null || levelid.equals("")) {
                            levelid = "0";
                        }
                        //处理黑名单拉黑的CUSTOMERID2更新
                        if (CUSTOMERID2 == null || CUSTOMERID2.equals("")) {
                            def updateuserid = "update customer set CUSTOMERID2=? where stringfield9 =? and stringfield105 is null";
                            def updateuseridresult = jt.update(updateuserid, userid, userid);
                            log.debug("updateuserid" + updateuserid);
                            log.debug("updateuseridresult" + updateuseridresult);
                            log.debug("customer表修改客户CUSTOMERID2成功");
                        }

                        //返回成功的查询结果
                        JSONObject jsonALL3 = new JSONObject();
                        jsonALL3.put("state", "1");
                        jsonALL3.put("success", "true");

                        log.debug("levelid:" + levelid);
                        //查询数据库中语言、会员等级匹配的队列queueid
                        queue = getqueueid(userid, language, levelid, link, jt);


                        // M+ 投资专区
                        if (whapp_from.equals("APPDR")) {
                            if (lang.equals("zh_cn") || lang.equals("zh_hk")) {
                                queue = 22;
                            } else {
                                queue = 21;
                            }
                        }
                        log.debug("M+ 投资专区队列识别: from:" + whapp_from + " lang:" + lang + " 识别结果queue:" + queue);
                        jsonALL3.put("queue", queue);
                        jsonALL3.put("msg", "接口调用成功......");
                        JSONObject json2 = new JSONObject();
                        json2.put("loginName", userid);
                        json2.put("password", password);
                        jsonALL3.put("result", json2);
                        return jsonALL3;
                    }
                }

            } else {
                if (language == "101") {
                    queue = 14;//简体普通队列-机器人
                } else if (language == "102" || language == "103") {
                    queue = 13;//繁体普通队列-机器人
                } else {
                    queue = 13;//繁体普通队列-机器人
                }
                //返回失败的结果
                JSONObject jsonALL1 = new JSONObject();

                // M+ 投资专区
                if (whapp_from.equals("APPDR")) {
                    if (lang.equals("zh_cn") || lang.equals("zh_hk")) {
                        queue = 22;
                    } else {
                        queue = 21;
                    }
                }
                log.debug("M+ 投资专区队列识别: from:" + whapp_from + " lang:" + lang + " 识别结果queue:" + queue);
                jsonALL1.put("queue", queue);
                jsonALL1.put("state", "0");
                jsonALL1.put("success", "false");
                jsonALL1.put("msg", "接口调用失败,入参匹配不到相应客户......");
                return jsonALL1;
            }
        }

    }

    // 调用华盛客户信息接口获取信息
    public static String Querypromocode(String injson) {

        long startTime = System.currentTimeMillis();
        log.debug("调用华盛客户信息接口-处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL + "/customer/query-ext";
            log.debug("调用华盛客户信息接口-doURL:" + doURL);
            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("调用华盛客户信息接口-getResult:" + getResult);

            //解析返回信息
            JSONObject jsonObject = JSONObject.parseObject(getResult, Feature.OrderedField);
            String code = jsonObject.get("code");

            log.debug("调用华盛客户信息接口-code:" + code);
            if (code == "00000") {
                reJson = getResult;
            } else {
                String msg = jsonObject.get("msg");
                reJson = "{\"code\":\"-1\",\"result\":\"用户会员等级、地区获取失败(" + msg + ")\"}";
            }

        } catch (Exception e) {
            log.error("调用华盛客户信息接口-接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"code\":\"-1\",\"result\":\"接口异常\"}";
        }
        return reJson;
    }

    // 查询数据库中语言、会员等级匹配的队列queueid
    public static String getqueueid(String userid, String language, String levelid, String link, JdbcTemplate jt) {

        def queueid;
        def handlegroupid;

        log.debug("link:" + link);
        //传入埋点信息值判断，如link为空默认机器人
        if (link == "") {
            if (language == "101") {
                queueid = 14;//简体普通队列--机器人
            }
            if (language == "102" || language == "103") {
                queueid = 13;//繁体普通队列--机器人
            }
            return queueid;
        }

        //优先查询归属顾问的区别，大陆顾问还是香港顾问来区分语种【大陆-简体中文、香港-繁体】；
        //如无归属服务顾问，则按客户端传入语种判断；如语种无参数，则默认简体；

        //20230606调整：网聊简繁体的队列分配调整
        //去除服务顾问的判断，  简体进简体  繁体进繁体  传英文或其他语言默认进繁体。Elite_2023_06
        /*
        def selecthandlegroupidSql = "Select o.Handlegroup_Id As handlegroupid From Objective o Left Join Customer c On o.Customer_Guid = c.Customer_Guid Where c.Customer_Id = ? And o.Map_Id = 'MY48ZX'";
        log.debug("selecthandlegroupidSql" + selecthandlegroupidSql);
        def handlegroupidsql = jt.queryForList(selecthandlegroupidSql, userid);
        log.debug("handlegroupidsql：" + handlegroupidsql);
        log.debug("size：" + handlegroupidsql.size());

        if (handlegroupidsql.size() > 0) {
            def handlegroupidmap = handlegroupidsql[0];
            handlegroupid = handlegroupidmap.get("handlegroupid");
            log.debug("handlegroupid:" + handlegroupid);
        } else {
            handlegroupid = "";
        }

        def selectqueueidSql;
        def queueidsql;
        //香港顾问
        if (handlegroupid == "QUF3T6") {
            selectqueueidSql = "select queueid from coilinqueue where type=? and levelid=?";
            queueidsql = jt.queryForList(selectqueueidSql, "2", levelid);
        } else if (handlegroupid != "") {//否则按大陆
            selectqueueidSql = "select queueid from coilinqueue where type=? and levelid=?";
            queueidsql = jt.queryForList(selectqueueidSql, "1", levelid);
        } else {//默认走语种判断
            selectqueueidSql = "select queueid from coilinqueue where language=? and levelid=?";
            queueidsql = jt.queryForList(selectqueueidSql, language, levelid);
        }
        */

        def selectqueueidSql;
        def queueidsql;
        //默认走语种判断
        selectqueueidSql = "select queueid from coilinqueue where language=? and levelid=?";
        queueidsql = jt.queryForList(selectqueueidSql, language, levelid);

        log.debug("selectqueueidSql" + selectqueueidSql);
        log.debug("queueidsql：" + queueidsql);
        log.debug("size：" + queueidsql.size());

        if (queueidsql.size() > 0) {
            def queueidmap = queueidsql[0];
            queueid = queueidmap.get("queueid");
            log.debug("queueid:" + queueid);
        } else {//兜底保护 --对于会员等级为空的场景
            if (language == "101") {
                queueid = 1;//简体普通队列
            } else if (language == "102" || language == "103") {
                queueid = 3;//繁体普通队列
            } else {
                queueid = 3;//繁体普通队列
            }

        }

        if (queueid != null && !queueid.equals("")) {
            queueid = queueid;
        } else {
            if (language == "101") {
                queueid = 14;//简体普通队列--机器人
            } else if (language == "102" || language == "103") {
                queueid = 13;//繁体普通队列--机器人
            }
        }
        return queueid;
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }

    /**
     * @param str :
     * @return String 用户号
     * @author LiJT
     * @description WhatsApp进线客户处理逻辑
     * @date 2023-01-28 17:10
     */
    public static JSONObject doWhatsAppMain(EliteBean eliteBean, JdbcTemplate jt, String in_UserID, String whapp_from, String whapp_to, String department) {

        // 初始化返回参数
        JSONObject chatResult = new JSONObject();
        chatResult.put("state", "1");
        chatResult.put("success", "true");

        // 检查是否是WhatsApp进线(WhatsApp的进线需要From和To都不为空)
        if (!KHUtil.isNull(whapp_to) && !KHUtil.isNull(whapp_from)) {
            String selectType = "";
            // 处理WhatsApp进线号码国际号码区号
            String whapp_to_enc = KHHSTUtil.getPhoneNo(eliteBean, whapp_to); // WhatsApp账号去除前缀
            String whapp_to_type = whapp_to.startsWith("+") ? "+" : "00"; // WhatsApp账号类别识别
            log.debug("WhatsApp客户手机号码处理-去除前缀:" + whapp_to_enc + " 类别识别:" + whapp_to_type);

            // 检查当前客户是否有专属坐席
            List<Map<String, Object>> selectCustResult = new ArrayList<>();
            String selectLangSQL = "";
            //区分客户校验
            if (department == "Esop") {
                selectLangSQL = '''Select R2.Customer_Guid,
                                       R2.Customer_Id,
                                       R2.Stringfield9,
                                       Case
                                         When R2.Mobile = ? Then
                                          'MOBILE'
                                         Else
                                          ''
                                       End As Selecttype,
                                     Case
                                       When R2.Open_Id = ? Then
                                        1
                                       When R2.Webchat_Target_Id = ? Then
                                        2
                                       When R2.Open_Id Like Concat('%', ?) Then
                                        3
                                       When R2.Webchat_Target_Id Like Concat('%', ?) Then
                                        4
                                       When R2.Mobile = ? Then
                                        5
                                       Else
                                        99
                                     End As selectLevel
                                  From Customer R2
                                 Where 1 = 1 and stringfield105='Esop'
                                   And (R2.Open_Id = ? Or R2.Open_Id Like Concat('%', ?) Or R2.Webchat_Target_Id = ? Or
                                       R2.Webchat_Target_Id Like Concat('%', ?) Or R2.Mobile = ?) Order By 5 Limit 1''';
            } else {//按华盛通客户
                selectLangSQL = '''Select R2.Customer_Guid,
                                       R2.Customer_Id,
                                       R2.Stringfield9,
                                       Case
                                         When R2.Mobile = ? Then
                                          'MOBILE'
                                         Else
                                          ''
                                       End As Selecttype,
                                     Case
                                       When R2.Open_Id = ? Then
                                        1
                                       When R2.Webchat_Target_Id = ? Then
                                        2
                                       When R2.Open_Id Like Concat('%', ?) Then
                                        3
                                       When R2.Webchat_Target_Id Like Concat('%', ?) Then
                                        4
                                       When R2.Mobile = ? Then
                                        5
                                       Else
                                        99
                                     End As selectLevel
                                  From Customer R2
                                 Where 1 = 1 and stringfield105 is null
                                   And (R2.Open_Id = ? Or R2.Open_Id Like Concat('%', ?) Or R2.Webchat_Target_Id = ? Or
                                       R2.Webchat_Target_Id Like Concat('%', ?) Or R2.Mobile = ?) Order By 5 Limit 1''';
            }

            selectCustResult = jt.queryForList(selectLangSQL, whapp_to, whapp_to, whapp_to, whapp_to_enc, whapp_to_enc, whapp_to_enc, whapp_to, whapp_to_enc, whapp_to, whapp_to_enc, whapp_to_enc);
            log.debug("检查当前客户信息是否存在:" + selectCustResult.toString());

            // 检查发送账号是否是服顾账号
            List<Map<String, Object>> selectFGResult = new ArrayList<>();
            String selectFGSQL = '''Select R1.Staff_Id, R1.Staffname From Staff R1 Where R1.Ewu_Id = ?''';
            selectFGResult = jt.queryForList(selectFGSQL, whapp_from);
            log.debug("检查发送账号是否是服顾账号:" + selectFGResult.toString());

            // 根据进线账号控制逻辑
            if (selectFGResult.size() == 0) {
                // 客服账号
                if (selectCustResult.size() == 0) {
                    // 客户信息不存在-新增
                    String re_Customer_Guid = "WHATSAPP_" + KHUtil.getRandomString(27);
                    String re_StringField9 = whapp_to;
                    selectType = "";
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    String insertCustSQL = "";

                    //区分客户校验
                    if (department == "Esop") {
                        insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS,stringfield105)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?,'Esop')''';
                    } else {//按华盛通客户
                        insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?)''';
                    }

                    int insertCust = jt.update(insertCustSQL, re_Customer_Guid, "", re_StringField9, "SELITE", "SELITE", whapp_to, "", "", "", "", whapp_to, whapp_to, whapp_to_enc);
                    log.debug("新增本地对应客户WhatsApp信息 DB操作数量:" + insertCust);

                    //区分客户校验
                    if (department == "Esop") {
                        chatResult.put("queue", 21);
                    } else {//按华盛通客户 按繁体
                        chatResult.put("queue", 13);
                    }
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to);
                    chatResult.put("msg", "接口调用成功(WhatsApp客服账号-新增)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                } else {
                    // 客户信息存在-查询
                    String re_Customer_Guid = selectCustResult.get(0).get("Customer_Guid").toString();
                    String re_StringField9 = selectCustResult.get(0).get("Stringfield9").toString();
                    selectType = selectCustResult.get(0).get("selectType").toString();
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    String updateCustSQL = '''Update Customer
                                           Set Icon_Url = '/ngs/js/plugins/chat/images/whatsapp.png',
                                               Open_Id = Case
                                                           When ('MOBILE' = ? And '00' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                            Replace(?, '+', '00')
                                                           Else
                                                            Open_Id
                                                         End,
                                               Webchat_Target_Id = Case
                                                                     When ('MOBILE' = ? And '+' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                                      ?
                                                                     Else
                                                                      Webchat_Target_Id
                                                                   End,OTHERS= ? 
                                         Where Customer_Guid = ?''';
                    int updateCust = jt.update(updateCustSQL, selectType, whapp_to_type, whapp_to, selectType, whapp_to_type, whapp_to, whapp_to_enc, re_Customer_Guid);
                    log.debug("更新本地对应客户WhatsApp信息 DB操作数量:" + updateCust);

                    //区分客户校验
                    if (department == "Esop") {
                        chatResult.put("queue", 21);
                    } else {//按华盛通客户 按繁体
                        chatResult.put("queue", 13);
                    }
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to.replace("+", "00"));
                    chatResult.put("msg", "接口调用成功(WhatsApp客服账号-更新)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                }

            } else {
                // 服顾账号
                String re_Staff_Id = selectFGResult.get(0).get("Staff_Id").toString();
                if (selectCustResult.size() == 0) {
                    // 客户信息不存在-新增
                    String re_Customer_Guid = "WHATSAPP_" + KHUtil.getRandomString(27);
                    String re_StringField9 = whapp_to;
                    selectType = "";
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    String insertCustSQL = '''Insert Into Customer
                                                  (Customer_Guid,
                                                   Customer_Id,
                                                   Stringfield9,
                                                   Createddate,
                                                   Createdby,
                                                   Modifieddate,
                                                   Modifiedby,
                                                   Customername,
                                                   Customerlevel,
                                                   Sq_15,
                                                   Sq_13,
                                                   Sq_14,Icon_Url,Open_Id,Webchat_Target_Id,OTHERS)
                                                Values
                                                  (?, ?, ?, Now(), ?, Now(), ?, ?, ?, ?, ?, ?,'/ngs/js/plugins/chat/images/whatsapp.png',?,?,?)''';
                    int insertCust = jt.update(insertCustSQL, re_Customer_Guid, "", re_StringField9, "SELITE", "SELITE", whapp_to, "", "", "", "", whapp_to, whapp_to, whapp_to_enc);
                    log.debug("新增本地对应客户WhatsApp信息 DB操作数量:" + insertCust);

                    String insertRouteSQL = '''Insert Into Chat_Multichannel_Route
                                      (Route_Guid,
                                       Customer_Guid,
                                       Openid,
                                       Ownerstaff_Id,
                                       Curvisitchannel,
                                       Firstvisittime,
                                       Curvisittime,
                                       Bind_Status,
                                       Lastupdateinfotime,
                                       Ower_Id)
                                    Values
                                      (Uuid(), ?, ?, ?, 'WC', Now(), Now(), 1, Now(), ?)''';
                    int insertRoute = jt.update(insertRouteSQL, re_Customer_Guid, "", re_Staff_Id, whapp_from);
                    log.debug("新增本地对应客户WhatsApp路由信息 DB操作数量:" + insertRoute);

                    chatResult.put("queue", 15);
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to);
                    chatResult.put("msg", "接口调用成功(WhatsApp服顾账号-新增)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                } else {
                    // 客户信息存在-查询
                    String re_Customer_Guid = selectCustResult.get(0).get("Customer_Guid").toString();
                    String re_StringField9 = selectCustResult.get(0).get("Stringfield9").toString();
                    selectType = selectCustResult.get(0).get("selectType").toString();
                    log.debug("WhatsApp匹配内部客户的方式:" + selectType);

                    // 服顾账号&客户信息存在-检查专属客户信息表是否存在
                    String selectRouteSQL = '''Select Route_Guid
                                                  From Chat_Multichannel_Route
                                                 Where Customer_Guid = ?
                                                   And Ownerstaff_Id = ?
                                                   And Bind_Status = 1''';
                    List<Map<String, Object>> selectRouteResult = jt.queryForList(selectRouteSQL, re_Customer_Guid, re_Staff_Id);
                    log.debug("检查专属客户信息表是否存在:" + selectRouteResult.toString());

                    if (selectRouteResult.size() == 0) {
                        // 检查专属客户信息表不存在-新增
                        String Route_Guid = KHUtil.getRandomString(36);
                        String insertRouteSQL = '''Insert Into Chat_Multichannel_Route
                                      (Route_Guid,
                                       Customer_Guid,
                                       Openid,
                                       Ownerstaff_Id,
                                       Curvisitchannel,
                                       Firstvisittime,
                                       Curvisittime,
                                       Bind_Status,
                                       Lastupdateinfotime,
                                       Ower_Id)
                                    Values
                                      (?, ?, ?, ?, 'WC', Now(), Now(), 1, Now(), ?)''';
                        int insertRoute = jt.update(insertRouteSQL, Route_Guid, re_Customer_Guid, "", re_Staff_Id, whapp_from);
                        log.debug("新增本地对应客户WhatsApp路由信息 DB操作数量:" + insertRoute + " Route_Guid:" + Route_Guid);
                    }

                    String updateCustSQL = '''Update Customer
                                           Set Icon_Url = '/ngs/js/plugins/chat/images/whatsapp.png',
                                               Open_Id = Case
                                                           When ('MOBILE' = ? And '00' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                            Replace(?, '+', '00')
                                                           Else
                                                            Open_Id
                                                         End,
                                               Webchat_Target_Id = Case
                                                                     When ('MOBILE' = ? And '+' = ?) Or Open_Id Is Null Or Open_Id != '' Then
                                                                      ?
                                                                     Else
                                                                      Webchat_Target_Id
                                                                   End,OTHERS= ? 
                                         Where Customer_Guid = ?''';
                    int updateCust = jt.update(updateCustSQL, selectType, whapp_to_type, whapp_to, selectType, whapp_to_type, whapp_to, whapp_to_enc, re_Customer_Guid);
                    log.debug("更新本地对应客户WhatsApp信息 DB操作数量:" + updateCust);

                    chatResult.put("queue", 15);
                    chatResult.put("clientGuid", re_Customer_Guid);
                    chatResult.put("openId", whapp_to.replace("+", "00"));
                    chatResult.put("msg", "接口调用成功(WhatsApp服顾账号-更新)");

                    JSONObject accountJson = new JSONObject();
                    accountJson.put("loginName", re_StringField9);
                    accountJson.put("password", "");
                    chatResult.put("result", accountJson);

                }
            }

        } else {
            String whapp_to_enc = KHHSTUtil.getPhoneNo(eliteBean, whapp_to); // WhatsApp账号去除前缀

            // 进线如果不存在UserID则通过进线号码查询一下
            if (KHUtil.isNull(in_UserID) && !KHUtil.isNull(whapp_to)) {
                String selectLangSQL = '''Select R2.Customer_Guid,
                                       R2.Customer_Id,
                                       R2.Stringfield9,
                                       Case
                                         When R2.Mobile = ? Then
                                          'MOBILE'
                                         Else
                                          ''
                                       End As Selecttype
                                  From Customer R2
                                 Where 1 = 1
                                   And (R2.Open_Id = ? Or R2.Open_Id Like Concat('%', ?) Or R2.Webchat_Target_Id = ? Or
                                       R2.Webchat_Target_Id Like Concat('%', ?) Or R2.Mobile = ?) Limit 1''';
                List<Map<String, Object>> selectCustResult = jt.queryForList(selectLangSQL, whapp_to, whapp_to, whapp_to_enc, whapp_to, whapp_to_enc, whapp_to_enc);
                log.debug("非WhatsApp进线-检查当前客户信息是否存在:" + selectCustResult.toString());

                if (selectCustResult.size() > 0) {
                    String re_UserID = selectCustResult.get(0).get("Stringfield9").toString();

                    chatResult.put("state", "0");
                    chatResult.put("userid", re_UserID);
                    chatResult.put("msg", "非WhatsApp进线-查询到本地UserID-" + re_UserID);

                } else {
                    chatResult.put("state", "-1");
                    chatResult.put("msg", "非WhatsApp进线-未查询到本地UserID");

                }

            } else {
                chatResult.put("state", "-2");
                chatResult.put("msg", "非WhatsApp进线-不满足查询本地账号");

            }
            log.debug("非WhatsApp进线-处理客户信息结果:" + chatResult.toString());
        }
        return chatResult;

    }
}